package com.skrivet.plugins.web.impl.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.ContextAttributes;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author brother N
 * @version 1.0
 * @description: TODO
 * @date 2022/1/25 10:39
 */
@Configuration
public class ObjectMapperConfig {
    @Bean
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper =builder.createXmlMapper(false).build();
        //表示转换时需要进行翻译
        objectMapper.setConfig(objectMapper.getSerializationConfig().with(ContextAttributes.getEmpty().withSharedAttribute("translate", true)));
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new StdDeserializer<String>(String.class) {
            @Override
            public String deserialize(JsonParser p, DeserializationContext context) throws IOException, JsonProcessingException {
                String result = StringDeserializer.instance.deserialize(p, context);
                if (StringUtils.isEmpty(result)) {
                    return null;
                }
                return result;
            }
        });
        //指定遇到date按照这种格式转换
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(fmt);
        objectMapper.registerModule(module);
        return new MappingJackson2HttpMessageConverter(objectMapper);
    }
}
